import React, { useState,useEffect } from 'react';
import { View, TextInput, Button, Alert, StyleSheet } from 'react-native';
import axios from 'axios';
import { useNavigation } from '@react-navigation/native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import Toast from 'react-native-toast-message';

export default function ChangeMyselfScreen() {
    const navigation = useNavigation();
    const [password, setPassword] = useState('');
    // const phone = JSON.stringify(route.params.phone)
    const [userInfo, setUserInfo] = useState({});
    const [username, setUsername] = useState('');
    useEffect(() => {
        (async () => {
            const userinfo = await AsyncStorage.getItem('userInfo');
            if (userinfo) {
                setUserInfo(JSON.parse(userinfo));
            }
        })();
    }, []);
    useEffect(() => {
        (async () => {
            if(userInfo.username){
                setUsername(userInfo.username)
            }
        })();
    }, [userInfo]);
    const changeMyself = () => {
        axios.post('http://47.111.227.58:3000/users/updateUsername', {
                username: username,
                id: userInfo.id
        })
            .then(function (res) {
                console.log(res.data);
                if (res.data.code == 200) {
                    Toast.show({
                        type: 'success',
                        text1: res.data.msg,
                    });
                    userInfo.username = username
                    AsyncStorage.setItem('userInfo', JSON.stringify(userInfo));
                    navigation.navigate('个人信息');
                } else {
                    Toast.show({
                        type: 'error',
                        text1: res.data.msg,
                    });
                }
            })
            .catch(function (error) {
                console.log(error);
            });
    };

    return (
        <View style={{ flex: 1, justifyContent: 'center', padding: 16, backgroundColor: '#FFF' }}>
            <TextInput
                style={{ height: 40, borderColor: '#808080', borderWidth: 1, marginBottom: 16, borderRadius: 5, paddingLeft: 10 }}
                onChangeText={setUsername}
                value={username}
                placeholder="请输入新的名称"
            />
            <Button
                title="确定修改"
                onPress={changeMyself}
                color="#EB7A76"
            />
        </View>
    );
}
